package com.techbrand.lb7.web.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.techbrand.lb7.domain.Customer;

public class CustomerValidator implements Validator {

	private LandlinePhoneValidator landlinePhoneValidator;
	private MobilePhoneValidator mobilePhoneValidator;
	private PersonValidator personValidator;
	private AddressValidator addressValidator;
	
	public AddressValidator getAddressValidator() {
		return addressValidator;
	}

	public void setAddressValidator(AddressValidator addressValidator) {
		this.addressValidator = addressValidator;
	}

	public PersonValidator getPersonValidator() {
		return personValidator;
	}

	public void setPersonValidator(PersonValidator personValidator) {
		this.personValidator = personValidator;
	}

	public MobilePhoneValidator getMobilePhoneValidator() {
		return mobilePhoneValidator;
	}

	public void setMobilePhoneValidator(MobilePhoneValidator mobilePhoneValidator) {
		this.mobilePhoneValidator = mobilePhoneValidator;
	}

	public LandlinePhoneValidator getLandlinePhoneValidator() {
		return landlinePhoneValidator;
	}

	public void setLandlinePhoneValidator(LandlinePhoneValidator landlinePhoneValidator) {
		this.landlinePhoneValidator = landlinePhoneValidator;
	}

	@SuppressWarnings("rawtypes")
	public boolean supports(Class clazz) {
		return Customer.class.isAssignableFrom(clazz);
	}
	
	public void validate(Object obj, Errors errors) {
		Customer cust = (Customer) obj;
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerName", "required");
		
		try {
			errors.pushNestedPath("contactPerson");
			ValidationUtils.invokeValidator(personValidator, cust.getContactPerson(), errors);
		} finally {
			errors.popNestedPath();
		}
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mobile", "required");
		
		ValidationUtils.invokeValidator(landlinePhoneValidator, cust.getPhone(), errors);
		ValidationUtils.invokeValidator(mobilePhoneValidator, cust.getMobile(), errors);
		
		try {
			errors.pushNestedPath("residentAddress");
			ValidationUtils.invokeValidator(addressValidator, cust.getResidentAddress(), errors);
		} finally {
			errors.popNestedPath();
		}
	}
}
